package com.zw.admin.server.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.sun.org.apache.xpath.internal.operations.Bool;
import com.zw.admin.server.dao.SpaceDao;
import com.zw.admin.server.dto.SpaceNode;
import com.zw.admin.server.model.*;
import com.zw.admin.server.page.table.PageTableHandler;
import com.zw.admin.server.page.table.PageTableRequest;
import com.zw.admin.server.page.table.PageTableResponse;
import com.zw.admin.server.service.DeviceService;
import com.zw.admin.server.service.SpaceService;
import com.zw.admin.server.utils.UserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


@Api(tags = "空间")
@RestController
@RequestMapping("/space")
public class SpaceController {

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private SpaceService spaceService;

    @Autowired
    private SpaceDao spaceDao;

    @GetMapping("/addSpace")
    public String addSpace(String spaceName, String parentId) {

        User user = UserUtil.getCurrentUser();

        HashMap<String, Object> returnMap = Maps.newHashMap();

        Space space = new Space();
        space.setSpaceName(spaceName);
        space.setParentId(parentId);
        int isSave = 0;
         int insertId = spaceService.saveOrUpdateSpace(space);
        returnMap.put("code", insertId == 1 ? 200 : 0); //返回1，表示存储成功
        return JSON.toJSONString(returnMap);
    }

    @GetMapping("/editSpaceName")
    @ApiOperation(value = "修改空间名称")
    public String editSpaceName(Long spaceId, String spaceName) {
        spaceService.editSpaceName(spaceId, spaceName);
        JSONObject result = new JSONObject();
        result.put("code", 200);
        result.put("msg", "修改成功");
        return result.toJSONString();
    }

    @GetMapping("/delSpace")
    public String delSpace(Long spaceId) {

        HashMap<String, Object> returnMap = Maps.newHashMap();

        if (spaceService.delSpace(spaceId) > 0) {
            //delSpaceDevice(spaceId.toString(),spaceService.getSpaceDeviceIds(spaceId));
            return "1";
        }
        return "0";
    }

    @GetMapping("/getSpaceList")
    public String getSpaceList() {
        return JSON.toJSONString(spaceDao.getSpaceList());
    }

    @GetMapping("/delSpaceDevice")
    public String delSpaceDevice(String spaceId, String deviceIds) {
        String[] split = deviceIds.split(",");
        ArrayList<String> ids = new ArrayList<>();
        for(int i =0; i<split.length; i++){
            ids.add(split[i]);
        }
        spaceService.delSpaceDevice(spaceId, ids);
        System.out.println(123);
        return "";
    }

    @GetMapping("/addSpaceDevice")
    public String addSpaceDevice(String spaceId, String deviceIds) {
        String[] split = deviceIds.split(",");
        ArrayList<String> ids = new ArrayList<>();
        for(int i =0; i<split.length; i++){
            ids.add(split[i]);
        }
        spaceService.addSpaceDevice(spaceId, ids);
        return "";
    }

    @GetMapping("/spaceList")
    @ApiOperation(value = "空间列表")
    public String spaceList(HttpServletRequest reques, HttpServletResponse response) {
        //查找所有顶级节点
        List<Space> topList = spaceService.getTopNode();

        ArrayList<Space> stack = new ArrayList<Space>();
        ArrayList<Space> spaceList = new ArrayList<Space>();
        //创建结果集栈,用栈遍历所有父子关系节点
        stack.addAll(topList);
        //创建待处理列表，用待处理列表创建对应父子级关系
        spaceList.addAll(topList);
        //结果栈非空，则一直处理
        while (!stack.isEmpty()) {

            //更新栈，并将所有节点加入待处理列表中
            if (!spaceService.getSubNode(stack.get(0).getSpaceId()).isEmpty()) {
                stack.addAll(spaceService.getSubNode(stack.get(0).getSpaceId()));
                spaceList.addAll(spaceService.getSubNode(stack.get(0).getSpaceId()));
            }
            //删除栈顶元素
            stack.remove(0);
        }
        //创建SpaceNodeList列表
        ArrayList<SpaceNode> nodeList = new ArrayList<SpaceNode>();
        for (Space space : spaceList) {
            SpaceNode node = new SpaceNode();
            node.setId(space.getSpaceId());
            node.setTitle(space.getSpaceName());
            node.setPId(space.getParentId());
            nodeList.add(node);
        }

        //倒序遍历待处理列表
        for (int i = nodeList.size() - 1; i >= 0; i--) {
            SpaceNode currentNode = nodeList.get(i);

            //父节点值非0，则表示此节点为子孙节点，则要插入到对应父节点中
            if (Integer.parseInt(currentNode.getPId()) != 0) {
                //遍历父节点，如果父节点有children则插入，为空则创建后插入
                for (int j = 0; j <= nodeList.size() - 1; j++) {
                    SpaceNode fathernode = nodeList.get(j);
                    //当前节点的父Id = 父节点的Id
                    if (Integer.parseInt(currentNode.getPId()) == Integer.parseInt(fathernode.getId())) {
                        if (fathernode.getChildren() == null) {
                            ArrayList<SpaceNode> children = new ArrayList<SpaceNode>();
                            children.add(currentNode);
                            fathernode.setChildren(children);
                        } else {
                            fathernode.getChildren().add(currentNode);
                        }
                        nodeList.remove(i);
                    }
                }
            }
        }
        return JSONObject.toJSONString(nodeList);
    }

    @GetMapping("/spaceDeviceList")
    @ApiOperation(value = "空间设备列表")
    public PageTableResponse spaceDeviceList(PageTableRequest request) {
        return new PageTableHandler(new PageTableHandler.CountHandler() {

            @Override
            public int count(PageTableRequest request) {
                return spaceService.countSpaceDevice(request.getParams());
            }
        }, new PageTableHandler.ListHandler() {

            @Override
            public List<Device> list(PageTableRequest request) {

                List<Device> list = spaceService.spaceDeviceList(request.getParams(), Integer.parseInt(request.getParams().get("offset").toString()), Integer.parseInt(request.getParams().get("limit").toString()));
                return list;
            }
        }).handle(request);
    }

    @GetMapping("/getSpaceDeviceList")
    @ApiOperation(value = "空间设备列表-用于策略，不分页")
    public List<Device> getSpaceDeviceList(String spaceId) {
        ArrayList<String> ids = new ArrayList<>();
        ids.add(spaceId);
        return spaceService.getSpaceDevice(ids);
    }


}
